package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.properties.AddressProperties;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private AddressProperties addressProperties;




    /**
     * 用户下单
     *
     * @param dto
     * @return
     */
    @Transactional   //0. 开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //获取当前登录人id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //根据地址簿id查询地址信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //用户地址与店铺地址距离判断
        String deliveryAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        if (!isInDeliveryScope(deliveryAddress)) {
            throw new OrderBusinessException(MessageConstant.NOT_IN_DILIVERY_SCOPE);
        }

        //根据用户id查询购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.getByUserId(userId);
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1. 构造订单数据对象orders，将orders插入到orders表中
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);

        //1.1 需要补充属性字段
        orders.setNumber(System.currentTimeMillis() + "");    //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);           //订单状态：1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(userId);                           //用户id
        orders.setOrderTime(LocalDateTime.now());           //下单时间
        orders.setPayStatus(Orders.UN_PAID);                //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());            //联系人手机号
        orders.setAddress(addressBook.getDetail());         //收货地址
        orders.setConsignee(addressBook.getConsignee());    //收货人
        orders.setUserName(user.getName());                 //下单人

        orderMapper.insert(orders);
        log.info("订单id: {}", orders.getId());

        //2. 构造订单明细列表数据orderDetails，将orderDetails插入到order_detail表中
        //2.1 根据购物车的商品数据，构造订单明细
        List<OrderDetail> orderDetails = new ArrayList<>();
        cartList.forEach(cart -> {
            //2.2 将购物车对象的数据拷贝给订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            //2.3 关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        orderDetailMapper.insertBatch(orderDetails);

        //3. 清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //4.构造vo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .build();
    }

    /**
     * 根据经纬度获得距离，判断是否在配送范围内
     * @param deliveryAddress
     * @return
     */
    private boolean isInDeliveryScope(String deliveryAddress) {
        // 获得经纬度
        String shopPosition = getLaAndLong(addressProperties.getAddress());
        String consigneePosition = getLaAndLong(deliveryAddress);

        // 构造数据
        Map params = new LinkedHashMap<String, String>();
        params.put("origin", shopPosition);
        params.put("destination", consigneePosition);
        params.put("ak", addressProperties.getAK());

        // 发送请求
        String s = HttpClientUtil.doGet(addressProperties.getDistanceURL(), params);

        // 第一种方式，JSON解析响应结果
        JSONObject jsonObject = JSON.parseObject(s);
        BigDecimal status = jsonObject.getBigDecimal("status");
        if (status.doubleValue() == 0) {
            JSONObject routes0 = (JSONObject) jsonObject.getJSONObject("result").getJSONArray("routes").get(0);
            BigDecimal distance = routes0.getBigDecimal("distance");
            log.info("配送距离：{}米", distance);
            if (distance.doubleValue() <= addressProperties.getScope()) {
                return true;
            }
        }

        // 第二种方式，裁剪字符串直接获取响应结果
        // if(s.contains("\"status\":0")) {
        //     String substring = s.substring(s.indexOf("distance\":") + 10, s.indexOf(",\"duration\":"));
        //     Long distance = Long.valueOf(substring);
        //     log.info("distance距离：{}", distance);
        //     if (distance <= 5000) {
        //         return true;
        //     }
        // }

        log.info("配送距离太远（>5km），下单失败了");
        return false;
    }

    /**
     * 发送请求获得经纬度
     * @param address
     * @return
     */
    private String getLaAndLong(String address) {
        log.info("发送地址：{}", address);

        // 构造数据
        Map params = new LinkedHashMap<String, String>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", addressProperties.getAK());
        // params.put("callback", "showLocation");

        String s = HttpClientUtil.doGet(addressProperties.getPositionURL(), params);

        // JSON解析数据
        JSONObject jsonObject = JSON.parseObject(s);
        BigDecimal lng = jsonObject.getJSONObject("result").getJSONObject("location").getBigDecimal("lng");
        BigDecimal lat = jsonObject.getJSONObject("result").getJSONObject("location").getBigDecimal("lat");

        // 剪切字符串获得数据（只需要小数点后5-6位）
        // String lng = s.substring(s.indexOf("lng\":") + 5, s.indexOf("lng\":") + 14);
        // String lat = s.substring(s.indexOf("lat\":") + 5, s.indexOf("lat\":") + 14);

        String location = lat + "," + lng;
        log.info("返回经纬度：{}", location);
        return location;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        /*// 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));*/

        //业务处理，修改订单状态、来单提醒
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //判断当前订单状态
        Orders orders = orderMapper.selectById(ordersRejectionDTO.getId());
        if (orders == null){//orders表中不存在该数据
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){//非待接单状态不能进行拒单操作
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //todo 进行退款操作 目前默认退款成功

        //创建orders对象 拒单后需要进行”自动退款“ 和 ”取消订单“ -- 补全订单状态和支付状态
        Orders ordersWithReject = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .status(Orders.CANCELLED)//已取消订单
                .payStatus(Orders.REFUND)//已退款
                .build();

        //更新数据库
        orderMapper.update(ordersWithReject);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryOrder(Long id) {
        //判断当前订单状态
        Orders orders = orderMapper.selectById(id);
        if (orders == null){//orders表中不存在该数据
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if (!orders.getStatus().equals(Orders.CONFIRMED)){//非已接单状态不能进行派送操作
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //创建orders对象
        Orders ordersWithDelivery = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();

        //更新数据库
        orderMapper.update(ordersWithDelivery);
    }


    /**
     * 取消订单
     * @param ordersId
     */
    @Override
    public void cancel(Long ordersId) {

        Orders orders = orderMapper.getByOrdersId(ordersId);

        orders.setStatus(Orders.CANCELLED);

        orderMapper.cancel(Orders.CANCELLED,ordersId);




    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetailByOrderId(Long id) {
        Orders orders= orderMapper.getByOrdersId(id);
        List<OrderDetail> list = orderDetailMapper.getByOrdersId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 查询订单
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
//        拿到用户id
        Long userId = BaseContext.getCurrentId();
//        拿到一个空的返回值
        OrderVO orderVO = new OrderVO();
//        根据前端传过来的订单id查询订单详情
        Orders orders = orderMapper.getById(id);
//        把查询到的订单信息值赋值给vo
        BeanUtils.copyProperties(orders, orderVO);
//        根据前端传过来的订单id查询查询订单明细表
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);
//        把订单明细表详情放入vo
      /*  orderVO.setOrderDetailList(orderDetailList);
        if (orders.getStatus().equals(Orders.PENDING_PAYMENT)) {
            Orders orders1 = orderMapper.getByS(orders.getStatus(), userId);
            OrderVO orderVO1 = new OrderVO();
            List<OrderDetail> o2 = orderDetailMapper.getById(orders1.getId());
            BeanUtils.copyProperties(orders1, orderVO1);
            orderVO1.setOrderDetailList(o2);
            return orderVO1;
        }
        if (orders.getStatus().equals(Orders.CANCELLED)) {
            Orders orders2 = orderMapper.getByStatus(orders.getStatus(), userId);
            OrderVO orderVO2 = new OrderVO();
            BeanUtils.copyProperties(orders2, orderVO2);
            List<OrderDetail> o3 = orderDetailMapper.getById(orders2.getId());
            orderVO2.setOrderDetailList(o3);
            return orderVO2;
        }*/
        return orderVO;
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO backCount() {
        //        统计待接单数量
        Integer counttoBeConfirmed= orderMapper.counttoBeConfirmed(Orders.TO_BE_CONFIRMED);
        //        统计待派送数量
        Integer confirmed= orderMapper.confirmed(Orders.CONFIRMED);
        //        统计派送中数量
        Integer deliveryInProgress= orderMapper.deliveryInProgress(Orders.DELIVERY_IN_PROGRESS);
        //给返回值赋值
        OrderStatisticsVO statisticsVO=new OrderStatisticsVO();
        statisticsVO.setToBeConfirmed(counttoBeConfirmed);
        statisticsVO.setConfirmed(confirmed);
        statisticsVO.setDeliveryInProgress(deliveryInProgress);
        return statisticsVO;
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 根据订单id获取订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 判断订单详情是否为空，是就抛异常
        if (orderDetailList == null || orderDetailList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 遍历订单详情集合
        for (OrderDetail orderDetail : orderDetailList) {
            // 构造购物车对象，复制订单详情的数据，并补齐属性
            ShoppingCart cart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, cart, "id");
            cart.setUserId(BaseContext.getCurrentId());
            cart.setCreateTime(LocalDateTime.now());
            // 重新添加购物车
            shoppingCartMapper.insert(cart);
        }
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        // 根据订单id获取订单对象
        Orders orders = orderMapper.getById(ordersConfirmDTO.getId());
        // 判断订单是否为空，如果是就抛异常
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 判断订单状态是否为待接单，如果不是就抛异常
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 设置订单状态为已接单
        orders.setStatus(Orders.CONFIRMED);
        // 更新订单数据
        orderMapper.update(orders);
    }

    /**
     * 用户端查询历史订单(即分页查询)
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult pageUser(int page, int pageSize, Integer status) {
        //用户只能查看自己的历史订单---OrdersPageQueryDTO
        PageHelper.startPage(page, pageSize);//传参
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());//当前用户id
        ordersPageQueryDTO.setStatus(status);//传参
        //分页查询---但是根据业务逻辑, 此处还要设置为条件查询 返回查到的订单集合
        Page<Orders> ordersPage = orderMapper.pageUser(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList();
        //构造返回结果
        for (Orders orders : ordersPage) {
            Long orderId = orders.getId();// 订单id
            // 查询订单明细 返回
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setOrderDetailList(orderDetails);
            list.add(orderVO);
        }
        return new PageResult(page, list);
    }

    /**
     * 商家订单搜索(条件查询)
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageAdmin(ordersPageQueryDTO);
        //构造返回对象
        return new PageResult(page.getTotal(), page.getResult()
        );
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getByOrderId(ordersCancelDTO.getId());
        Integer status = orders.getStatus();
        if (status == 2 || status == 6) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CANCELLED);
        if (status != 1) {
            refund(orders.getAmount());
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        Integer status = orders.getStatus();
        if (status == 4) {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            orderMapper.update(orders);
        } else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 退款伪代码
     *
     * @param orderMoney
     * @return
     */
    public boolean refund(BigDecimal orderMoney) {
        BigDecimal adminWallet = BigDecimal.valueOf(10000000);
        if (adminWallet.doubleValue() > orderMoney.doubleValue()) {
            adminWallet = adminWallet.subtract(orderMoney);
            return true;
        }
        return false;
    }
}
